<template>
  <div class="customer-list-container">
    <div class="page-header">
      <h1>{{ pageTitle || '客户管理' }}</h1>
      <p v-if="pageSubtitle" class="page-subtitle">{{ pageSubtitle }}</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="用户名、邮箱或姓名"
            clearable
            @clear="handleSearch"
            style="width: 260px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="全部"
            clearable
            @clear="handleSearch"
            style="width: 130px;"
          >
            <el-option label="激活" :value="true" />
            <el-option label="未激活" :value="false" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="邮件订阅">
          <el-select
            v-model="searchForm.newsletter_subscribed"
            placeholder="全部"
            clearable
            @clear="handleSearch"
            style="width: 130px;"
          >
            <el-option label="已订阅" :value="true" />
            <el-option label="未订阅" :value="false" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon total">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.total_customers }}</div>
          <div class="stat-label">总客户数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon active">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.active_customers }}</div>
          <div class="stat-label">活跃客户</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon newsletter">
          <el-icon><Message /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.newsletter_subscribers }}</div>
          <div class="stat-label">邮件订阅用户</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon revenue">
          <el-icon><Money /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">${{ parseFloat(stats.total_revenue).toFixed(2) }}</div>
          <div class="stat-label">总收入</div>
        </div>
      </div>
    </div>

    <!-- 客户列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="customerList" 
        v-loading="loading" 
        stripe
        row-key="id"
        style="width: 100%"
      >
        <el-table-column label="客户信息" min-width="200">
          <template #default="{ row }">
            <div class="customer-info">
              <el-avatar :size="40" :src="row.profile?.avatar" class="customer-avatar">
                {{ row.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="customer-details">
                <div class="customer-name">{{ row.full_name }}</div>
                <div class="customer-username">@{{ row.username }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="邮箱" prop="email" min-width="200" />
        
        <el-table-column label="电话" width="140">
          <template #default="{ row }">
            {{ row.profile?.phone || '暂无' }}
          </template>
        </el-table-column>

        <el-table-column label="公司名称" min-width="200">
          <template #default="{ row }">
            {{ row.profile?.company || '暂无' }}
          </template>
        </el-table-column>
        
        <!-- 地址列移除按需展示 -->
        
        <el-table-column label="订单数" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.profile?.total_orders || 0 }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="总消费" width="120" align="right">
          <template #default="{ row }">
            ${{ parseFloat(row.profile?.total_spent || 0).toFixed(2) }}
          </template>
        </el-table-column>
        
        <el-table-column label="邮件订阅" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="row.profile?.newsletter_subscribed ? 'success' : 'info'" size="small">
              {{ row.profile?.newsletter_subscribed ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              :loading="row._statusLoading"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="注册时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.date_joined) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)" :icon="View">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 客户详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="客户详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentCustomer" class="customer-detail">
        <div class="detail-header">
          <el-avatar :size="80" :src="currentCustomer.profile?.avatar">
            {{ currentCustomer.username.charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="header-info">
            <h2>{{ currentCustomer.full_name }}</h2>
            <p class="username">@{{ currentCustomer.username }}</p>
            <el-tag :type="currentCustomer.is_active ? 'success' : 'danger'">
              {{ currentCustomer.is_active ? '激活' : '未激活' }}
            </el-tag>
          </div>
        </div>

        <el-tabs>
          <el-tab-pane label="基本信息">
            <div class="info-grid">
              <div class="info-item">
                <label>邮箱</label>
                <span>{{ currentCustomer.email }}</span>
              </div>
              <div class="info-item">
                <label>电话</label>
                <span>{{ currentCustomer.profile?.phone || '暂无' }}</span>
              </div>
              <div class="info-item company-item">
                <label>公司名称</label>
                <div class="company-edit">
                  <el-input
                    v-model="companyDraft"
                    size="small"
                    placeholder="请输入公司名称"
                    style="max-width: 240px;"
                  />
                  <el-button
                    size="small"
                    type="primary"
                    :loading="savingCompany"
                    :disabled="savingCompany || companyDraft === (currentCustomer.profile?.company || '')"
                    @click="handleSaveCompany"
                  >
                    保存
                  </el-button>
                </div>
              </div>
              <div class="info-item">
                <label>名字</label>
                <span>{{ currentCustomer.first_name || '暂无' }}</span>
              </div>
              <div class="info-item">
                <label>姓氏</label>
                <span>{{ currentCustomer.last_name || '暂无' }}</span>
              </div>
              <div class="info-item">
                <label>邮件订阅</label>
                <span>{{ currentCustomer.profile?.newsletter_subscribed ? '已订阅' : '未订阅' }}</span>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="地址信息">
            <el-table
              v-if="currentCustomer?.addresses && currentCustomer.addresses.length"
              :data="sortedAddresses"
              size="small"
              style="width: 100%"
            >
              <el-table-column label="默认" width="70" align="center">
                <template #default="{ row }">
                  <el-tag v-if="row.is_default" type="success" size="small">默认</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="姓名" min-width="140">
                <template #default="{ row }">
                  {{ row.first_name }} {{ row.last_name }}
                </template>
              </el-table-column>
              <el-table-column label="电话" prop="phone" width="150" />
              <el-table-column label="公司" prop="company" min-width="120" />
              <el-table-column label="地址" min-width="260">
                <template #default="{ row }">
                  <div>
                    <div>{{ row.address_line1 }}</div>
                    <div v-if="row.address_line2">{{ row.address_line2 }}</div>
                    <div>{{ row.city }}, {{ row.state }} {{ row.postal_code }}</div>
                    <div>{{ row.country }}</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="no-addresses">暂无地址</div>
          </el-tab-pane>

          <el-tab-pane label="统计信息">
            <div class="info-grid">
              <div class="info-item">
                <label>总订单数</label>
                <span>{{ currentCustomer.profile?.total_orders || 0 }}</span>
              </div>
              <div class="info-item">
                <label>总消费</label>
                <span>${{ parseFloat(currentCustomer.profile?.total_spent || 0).toFixed(2) }}</span>
              </div>
              <div class="info-item">
                <label>注册时间</label>
                <span>{{ formatDate(currentCustomer.date_joined) }}</span>
              </div>
              <div class="info-item">
                <label>最后登录</label>
                <span>{{ currentCustomer.last_login ? formatDate(currentCustomer.last_login) : '从未登录' }}</span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="action-buttons">
          <el-button @click="handleResetPassword" type="warning" :icon="Lock">重置密码</el-button>
          <el-button @click="handleToggleStatus" :type="currentCustomer.is_active ? 'danger' : 'success'">
            {{ currentCustomer.is_active ? '停用' : '激活' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, User, Check, Message, Money, View, Lock } from '@element-plus/icons-vue'
import { getCustomers, getCustomerDetail, toggleCustomerActive, resetCustomerPassword, getCustomerStats, updateCustomer } from '@/api/customer'
import type { Customer, CustomerQueryParams } from '@/api/customer'
import dayjs from 'dayjs'
import { usePageMeta } from '@/composables/usePageMeta'

interface CustomerWithLoading extends Customer {
  _statusLoading?: boolean
}

const { pageTitle, pageSubtitle } = usePageMeta()

const loading = ref(false)
const customerList = ref<CustomerWithLoading[]>([])
const total = ref(0)
const dialogVisible = ref(false)
const currentCustomer = ref<Customer | null>(null)
const companyDraft = ref('')
const savingCompany = ref(false)
const sortedAddresses = computed(() => {
  const list = currentCustomer.value?.addresses ? [...currentCustomer.value.addresses] : []
  // 默认地址置顶，其余按创建时间倒序
  return list.sort((a, b) => {
    if (a.is_default && !b.is_default) return -1
    if (!a.is_default && b.is_default) return 1
    return dayjs(b.created_at).valueOf() - dayjs(a.created_at).valueOf()
  })
})

const searchForm = reactive({
  search: '',
  is_active: undefined as boolean | undefined,
  newsletter_subscribed: undefined as boolean | undefined,
  page: 1,
  page_size: 20
})

const stats = reactive({
  total_customers: 0,
  active_customers: 0,
  newsletter_subscribers: 0,
  total_orders: 0,
  total_revenue: '0.00'
})

watch(currentCustomer, (val) => {
  companyDraft.value = val?.profile?.company || ''
})

watch(dialogVisible, (visible) => {
  if (!visible) {
    companyDraft.value = ''
  } else if (currentCustomer.value) {
    companyDraft.value = currentCustomer.value.profile?.company || ''
  }
})

const loadCustomers = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      is_active: searchForm.is_active,
      newsletter_subscribed: searchForm.newsletter_subscribed
    } as CustomerQueryParams
    Object.keys(params).forEach((key) => {
      const k = key as keyof CustomerQueryParams
      if (params[k] === undefined || params[k] === '') {
        delete params[k]
      }
    })
    const res = await getCustomers(params)
    customerList.value = res.results.map(customer => ({ ...customer, _statusLoading: false }))
    total.value = res.count
  } catch (error) {
    ElMessage.error('加载客户失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const res = await getCustomerStats()
    Object.assign(stats, res)
  } catch (error) {
    console.error('Failed to load stats:', error)
  }
}

const handleSearch = () => {
  searchForm.page = 1
  loadCustomers()
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.is_active = undefined
  searchForm.newsletter_subscribed = undefined
  searchForm.page = 1
  loadCustomers()
}

const handleView = async (row: Customer) => {
  try {
    currentCustomer.value = await getCustomerDetail(row.id)
    companyDraft.value = currentCustomer.value.profile?.company || ''
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载客户详情失败')
  }
}

const handleStatusChange = async (row: CustomerWithLoading) => {
  row._statusLoading = true
  try {
    const res = await toggleCustomerActive(row.id)
    row.is_active = res.is_active
    ElMessage.success(res.message)
    loadStats()
  } catch (error) {
    row.is_active = !row.is_active
    ElMessage.error('状态更新失败')
  } finally {
    row._statusLoading = false
  }
}

const handleResetPassword = async () => {
  if (!currentCustomer.value) return
  
  try {
    const { value: newPassword } = await ElMessageBox.prompt(
      '请输入新密码',
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputValidator: (value) => {
          if (!value) {
            return '密码不能为空'
          }
          if (value.length < 6) {
            return '密码长度至少为6位'
          }
          return true
        }
      }
    )
    
    await resetCustomerPassword(currentCustomer.value.id, newPassword)
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置密码失败')
    }
  }
}

const handleToggleStatus = async () => {
  if (!currentCustomer.value) return
  
  try {
    const res = await toggleCustomerActive(currentCustomer.value.id)
    currentCustomer.value.is_active = res.is_active
    ElMessage.success(res.message)
    loadCustomers()
    loadStats()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

const handleSaveCompany = async () => {
  if (!currentCustomer.value) return
  
  savingCompany.value = true
  try {
    const nextCompany = companyDraft.value.trim()
    companyDraft.value = nextCompany
    const res = await updateCustomer(currentCustomer.value.id, {
      profile: { company: nextCompany }
    })
    if (currentCustomer.value.profile) {
      currentCustomer.value.profile.company = res.profile.company
    }
    const target = customerList.value.find(item => item.id === currentCustomer.value?.id)
    if (target?.profile) {
      target.profile.company = res.profile.company
    }
    ElMessage.success('公司名称已更新')
  } catch (error) {
    ElMessage.error('更新公司名称失败')
  } finally {
    savingCompany.value = false
  }
}

const handlePageChange = (page: number) => {
  searchForm.page = page
  loadCustomers()
}

const handleSizeChange = (size: number) => {
  searchForm.page_size = size
  searchForm.page = 1
  loadCustomers()
}

const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD')
}

const formatLocation = (profile: Customer['profile']) => {
  const parts = [profile.city, profile.state, profile.country].filter(Boolean)
  return parts.length > 0 ? parts.join(', ') : '暂无'
}

onMounted(() => {
  loadCustomers()
  loadStats()
})
</script>

<style scoped>
.customer-list-container {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #1a1a1a;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.filter-form {
  margin: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.newsletter {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #fda085 0%, #f6d365 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.table-card {
  border-radius: 8px;
}

.customer-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.customer-avatar {
  flex-shrink: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.customer-details {
  flex: 1;
  min-width: 0;
}

.customer-name {
  font-size: 14px;
  font-weight: 500;
  color: #1a1a1a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.customer-username {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.customer-detail {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 20px;
}

.header-info h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
}

.header-info .username {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-size: 12px;
  font-weight: 500;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-item span {
  font-size: 14px;
  color: #1a1a1a;
}

.company-item {
  align-items: flex-start;
}

.company-edit {
  display: flex;
  align-items: center;
  gap: 8px;
}

.company-edit :deep(.el-input) {
  flex: 1;
}

.action-buttons {
  display: flex;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
